<template>
  <div class="min-h-screen bg-gray-50">
    <div class="container">
      <div class="main-content">
        <!-- 左侧配置面板 -->
        <div class="left-panel">
          <h2 class="section-title">周期性排班配置</h2>
          <div class="config-options">
            <div class="dropdown">
              <button @click="toggleConfigType" class="dropdown-button">
                {{ configTypes[currentConfigType] }}
                <i class="fas fa-chevron-down"></i>
              </button>
              <div v-if="showConfigDropdown" class="dropdown-menu">
                <div
                  v-for="(type, index) in configTypes"
                  :key="index"
                  @click="selectConfigType(index)"
                  class="dropdown-item"
                >
                  {{ type }}
                </div>
              </div>
            </div>

            <!-- 第一个 -->
            <div v-if="currentConfigType === 0" class="config-group">
              <label class="label">
                <el-icon class="icon-aligned">
                  <StarFilled />
                </el-icon>
                <span style="width: 240px"
                  >每日班次数量
                  <el-tooltip content="一天值班的班次数量" placement="right">
                    <el-icon class="icon-aligned">
                      <QuestionFilled />
                    </el-icon> </el-tooltip
                ></span>
                <input
                  type="text"
                  v-model="config.shiftsPerDay"
                  class="input-field"
                  @change="updateTimeSlots"
                />
              </label>

              <!-- 新增标签输入框 -->
              <div class="custom-tag-input">
                <label class="label"
                  ><el-icon class="icon-aligned">
                    <Operation />
                  </el-icon>
                  <span style="width: 240px"
                    >选择各班次时间段
                    <el-tooltip content="选择各班次的时间段，将使用该时间段的无课时间" placement="right" >
                      <el-icon class="icon-aligned">
                        <QuestionFilled />
                      </el-icon> </el-tooltip
                  ></span>
                  <div class="input-group">
                    <el-select
                      v-model="selectedTimeSlot"
                      placeholder="选择班次时间段"
                      style="width: 180px"
                    >
                      <el-option
                        v-for="(slot, index) in time_slots"
                        :key="index"
                        :label="slot"
                        :value="slot"
                        :disabled="timeSlots.length >= parseInt(config.shiftsPerDay)"
                      />
                    </el-select>
                    <el-button
                      type="primary"
                      style="margin-left: 8px"
                      @click="addTimeSlotTag"
                      :disabled="
                        !selectedTimeSlot || timeSlots.length >= parseInt(config.shiftsPerDay)
                      "
                    >
                      添加
                    </el-button>
                  </div>
                </label>

                <div class="tags-container">
                  <el-tag
                    v-for="(tag, index) in timeSlots"
                    :key="index"
                    closable
                    @close="removeTimeSlot(index, tag.time)"
                    style="margin: 4px"
                  >
                    {{ tag.time }}
                  </el-tag>
                </div>
              </div>

              <div class="config-group">
                <label class="label">
                  <el-icon class="icon-aligned">
                    <UserFilled />
                  </el-icon>
                  <span style="width: 240px"
                    >每个班次人数范围
                    <el-tooltip
                      content="每个班次的人数范围，最小人数和最大人数，相等则固定人数"
                      placement="right"
                    >
                      <el-icon class="icon-aligned">
                        <QuestionFilled />
                      </el-icon> </el-tooltip
                  ></span>
                  <div class="input-group">
                    <input
                      type="text"
                      v-model="config.minPeople"
                      placeholder="最小人数"
                      class="input-field"
                    />-
                    <input
                      type="text"
                      v-model="config.maxPeople"
                      placeholder="最大人数"
                      class="input-field"
                    />
                  </div>
                </label>
              </div>

              <label class="label">
                <el-icon class="icon-aligned">
                  <Position />
                </el-icon>
                <span style="width: 240px"
                  >排班周期(周)
                  <el-tooltip content="排班周期，一周5天一个值班表" placement="right">
                    <el-icon class="icon-aligned">
                      <QuestionFilled />
                    </el-icon> </el-tooltip
                ></span>
                <input type="text" v-model="config.weeks" class="input-field" /> &nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;5&nbsp;&nbsp;天
              </label>

              <div class="config-group">
                <label class="label">
                  <el-icon class="icon-aligned">
                    <Shop />
                  </el-icon>
                  <span style="width: 240px"
                    >每人每个周期内班次范围
                    <el-tooltip
                      content="每人每个周期内班次范围，最小班次和最大班次，相等则固定班次"
                      placement="right"
                    >
                      <el-icon class="icon-aligned">
                        <QuestionFilled />
                      </el-icon> </el-tooltip
                  ></span>
                  <div class="input-group">
                    <input
                      type="text"
                      v-model="config.minShifts"
                      placeholder="最小班次"
                      class="input-field"
                    />-
                    <input
                      type="text"
                      v-model="config.maxShifts"
                      placeholder="最大班次"
                      class="input-field"
                    />
                  </div>
                </label>
              </div>

              <label class="label">
                <el-icon class="icon-aligned">
                  <Location />
                </el-icon>
                <span style="width: 240px"
                  >值班地点数量
                  <el-tooltip content="值班地点数量，以location_xx表示" placement="right">
                    <el-icon class="icon-aligned">
                      <QuestionFilled />
                    </el-icon> </el-tooltip
                ></span>
                <input type="text" v-model="config.locations" class="input-field" />
              </label>

              <div class="config-group">
                <label class="label">
                  <el-icon class="icon-aligned">
                    <Shop />
                  </el-icon>
                  <span style="width: 240px"
                    >一周（5天）内空闲班次范围
                    <el-tooltip
                      content="一周（5天）内空闲班次范围，最小空闲和最大空闲，相等则固定空闲班次"
                      placement="right"
                    >
                      <el-icon class="icon-aligned">
                        <QuestionFilled />
                      </el-icon> </el-tooltip
                  ></span>
                  <div class="input-group">
                    <input
                      type="text"
                      v-model="config.minFreeShifts"
                      placeholder="最小空闲"
                      class="input-field"
                    />-
                    <input
                      type="text"
                      v-model="config.maxFreeShifts"
                      placeholder="最大空闲"
                      class="input-field"
                    />
                  </div>
                </label>
              </div>

              <div class="config-group">
                <label class="label">
                  <el-icon class="icon-aligned">
                    <Timer />
                  </el-icon>
                  <span style="width: 240px"
                    >值班周次范围
                    <el-tooltip content="值班周次范围，从第几周开始到第几周结束" placement="right">
                      <el-icon class="icon-aligned">
                        <QuestionFilled />
                      </el-icon> </el-tooltip
                  ></span>
                  <div class="input-group">
                    <input type="text" v-model="config.startWeek" class="input-field" />-
                    <input type="text" v-model="config.endWeek" class="input-field" />
                  </div>
                </label>
              </div>

              <label class="label"
                ><el-icon class="icon-aligned">
                  <UserFilled />
                </el-icon>
                <span style="width: 240px"
                  >排除名单
                  <el-tooltip content="排除名单，将不会出现在排班表中，无可行解时，可修改排除名单" placement="right">
                    <el-icon class="icon-aligned">
                      <QuestionFilled />
                    </el-icon> </el-tooltip
                ></span>
                <div style="display: flex; align-items: center">
                  <el-select
                    v-model="config.exclude_name"
                    multiple
                    filterable
                    placeholder="选择排除名单"
                    class="input-field"
                    style="width: 360px"
                  >
                    <el-option
                      v-for="member in org_members"
                      :key="member.personal_info.student_id"
                      :label="member.personal_info.name"
                      :value="member.personal_info.name"
                    />
                  </el-select>
                  <el-button
                    type="danger"
                    size="small"
                    style="margin-left: 10px"
                    @click="config.exclude_name = []"
                    :disabled="config.exclude_name.length === 0"
                  >
                    X
                  </el-button>
                </div>
              </label>
              <label class="label">
                <el-icon class="icon-aligned">
                  <Aim />
                </el-icon>
                <span style="width: 240px"
                  >自定义约束
                  <el-tooltip content="强行设置某些班次空闲状态" placement="right">
                    <el-icon class="icon-aligned">
                      <QuestionFilled />
                    </el-icon> </el-tooltip
                ></span>
              </label>
              <div class="custom-tag-input">
                <!-- 输入框和添加按钮 -->
                <div class="input-group">
                  <el-select v-model="selected.week" placeholder="选择星期" style="width: 120px">
                    <el-option v-for="day in weekOptions" :key="day" :label="day" :value="day" />
                  </el-select>

                  <el-select
                    v-model="selected.number"
                    placeholder="选择班次"
                    style="width: 120px; margin-left: 8px"
                  >
                    <el-option
                      v-for="n in parseInt(config.shiftsPerDay)"
                      :key="n"
                      :label="n"
                      :value="n"
                    />
                  </el-select>

                  <el-select
                    v-model="selected.isNull"
                    placeholder="是否为空"
                    style="width: 120px; margin-left: 8px"
                  >
                    <el-option
                      v-for="item in nullOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>

                  <el-button
                    type="primary"
                    style="margin-left: 8px"
                    @click="addTag"
                    :disabled="!isSelectionComplete"
                  >
                    添加
                  </el-button>
                </div>

                <!-- 已添加的标签展示 -->
                <div class="tags-container">
                  <el-tag
                    v-for="(tag, index) in tags"
                    :key="index"
                    closable
                    @close="removeTag(index)"
                    style="margin: 4px"
                  >
                    {{ formatTag(tag) }}
                  </el-tag>
                </div>
              </div>
            </div>

            <!-- 第二个 -->
            <div v-if="currentConfigType === 1" class="config-group"></div>

            <div class="button-container">
              <el-button class="action-button" @click="startScheduling">开始排班</el-button>
            </div>
          </div>
        </div>

        <!-- 右侧预览表格 -->
        <div class="right-panel">
          <div class="preview-header">
            <h2 class="section-title">结果预览</h2>
            <div class="schedule-navigation">
              <el-button type="primary" @click="prevSchedule" :disabled="isFirstSchedule">
                上一个
              </el-button>
              <span style="margin: 0 16px">
                排班表 {{ (currentSchedule + 1).toString().padStart(2, '0') }} /
                {{ schedules.length.toString().padStart(2, '0') }}
              </span>
              <el-button type="primary" @click="nextSchedule" :disabled="isLastSchedule">
                下一个
              </el-button>
            </div>
          </div>

          <!-- 滚动内容容器 -->
          <div class="scroll-container">
            <!-- 当 rawData 不为空时显示表格 -->
            <div v-if="rawData.length > 0">
              <!-- 每个地点单独一个表格 -->
              <div v-for="location in locations" :key="location" class="location-table">
                <h3 class="location-title">{{ location.toUpperCase() }}</h3>
                <table class="schedule-table">
                  <thead>
                    <tr>
                      <th class="table-header">班次</th>
                      <th v-for="day in totalDays" :key="day" class="table-header shift-header">
                        Day {{ day }}
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="shift in totalShifts" :key="shift">
                      <td class="table-header shift-header">Shift {{ shift }}</td>
                      <td
                        v-for="day in totalDays"
                        :key="day"
                        class="shift-cell"
                        :class="{ 'empty-cell': !getStaff(location, day, shift).length }"
                      >
                        <div class="staff-tags">
                          <el-tag
                            v-for="(staff, index) in getStaff(location, day, shift)"
                            :key="index"
                            class="staff-tag"
                            type="info"
                            size="small"
                            :style="{
                              backgroundColor: getColorForStudent(staff),
                              borderColor: 'transparent',
                              color: getTextColor(getColorForStudent(staff)),
                            }"
                          >
                            {{ staff }}
                          </el-tag>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>

            <!-- 当 rawData 为空时显示无结果消息 -->
            <div v-else class="no-results">
              <el-empty :image-size="200" description="无可行解" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 使整个页面的宽度和高度铺满屏幕 */
html,
body {
  height: 100%;
  margin: 0;
}

/* 使容器宽度最大化并居中 */
.container {
  display: flex;
  justify-content: space-between;
  /* height: 90vh; 使容器高度填满整个视窗 */
  width: 100%;
  overflow: hidden;
}

.main-content {
  display: flex;
  width: 100%;
  height: 100%;
  min-height: 0; /* 修复flex容器滚动问题 */
}

.left-panel {
  flex: 0 0 30%;
  height: 94%;
  background-color: white;
  border-radius: 8px;
  /* box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); */
  padding: 24px;
  overflow-y: auto;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 94%;
  margin-left: 20px;
  margin-top: auto;
  margin-bottom: auto;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(0, 0, 0, 0.1);
  padding: 20px;
}
.scroll-container {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.location-table {
  margin-bottom: 30px;
}

.location-title {
  color: #606266;
  margin: 15px 0;
  font-size: 16px;
  font-weight: bold;
}

.schedule-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.table-header {
  background: #f5f7fa;
  color: #909399;
  font-weight: normal;
  padding: 12px;
  border: 1px solid #ebeef5;
  min-width: 80px;
}

.shift-header {
  text-align: center;
}

.day-header {
  background: #f5f7fa;
  padding: 12px;
  border: 1px solid #ebeef5;
  width: 60px;
}

.shift-cell {
  padding: 8px;
  border: 4px solid #ebeef5;
  min-width: 120px;
  height: 30px;
  /* display: flex; 启用flex布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

.staff-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  justify-content: center; /* 标签组水平居中 */
  align-content: center; /* 多行时垂直居中 */
  width: 100%; /* 填充单元格宽度 */
}

.staff-tag {
  margin: 2px;
  background: #f0f2f5;
  border-color: #e4e7ed;
  color: #333;
}

/* 其余样式与之前的保持一致 */
.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 32px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 24px;
}

.config-options {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.dropdown-button {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 8px 12px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: white;
  color: #333;
  cursor: pointer;
}

.dropdown-menu {
  position: absolute;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #ccc;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.dropdown-item {
  padding: 8px 12px;
  font-size: 14px;
  color: #333;
  cursor: pointer;
}

.dropdown-item:hover {
  background-color: #f7f7f7;
}

.config-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.label {
  font-size: 14px;
  color: #4a4a4a;
  display: flex;
  align-items: center; /* 使图标和文字垂直居中 */
  justify-content: flex-start; /* 使图标和文字左对齐 */
}

.icon-aligned {
  vertical-align: middle;
  margin-left: 8px;
  margin-right: 8px;
  line-height: 1; /* 确保图标与文字在同一行 */
}

.input-field {
  width: 50px;
  padding: 8px 12px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 8px;
  /* 居中 */
  text-align: center;
}

.input-group {
  display: flex;
  gap: 16px;
}

.button-container {
  padding-top: 16px;
}

.action-button {
  width: 100%;
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 600;
  background-color: #409eff;
  color: white;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-button:hover {
  background-color: #218838;
}

.actions {
  display: flex;
  gap: 8px;
}

.table-cell {
  color: #333;
}

.location-tag {
  display: inline-block;
  padding: 4px 8px;
  font-size: 12px;
  border-radius: 16px;
}

.location-blue {
  background-color: #e0f7fa;
  color: #00796b;
}

.location-green {
  background-color: #c8e6c9;
  color: #388e3c;
}

.location-purple {
  background-color: #e1bee7;
  color: #8e24aa;
}

.location-default {
  background-color: #f5f5f5;
  color: #757575;
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
  }

  .left-panel,
  .right-panel {
    width: 100%;
  }
}

.custom-tag-input {
  max-width: 800px;
}

.input-group {
  display: flex;
  align-items: center;
}

.tags-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
  min-height: 40px;
  margin-top: 10px;
}

.location-selector {
  margin-bottom: 20px;
}
.empty-cell {
  background-color: rgb(222, 221, 221);
}

/* 添加样式以美化"上一个"和"下一个"按钮的布局 */
.schedule-navigation {
  display: flex;
  align-items: center;
}

.no-results {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  font-size: 18px;
  color: #999;
}
</style>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import api from '../axios/api'
import { useRoute } from 'vue-router'
const route = useRoute()
// const org_id = ref('19')
const org_id = ref(route.params.orgId as string)
const org_members = ref<any[]>([])

const setOrgMembers = async (): Promise<void> => {
  const res = await api.getOrgMembers(org_id.value)
  org_members.value = res.data
  console.log(org_members.value)
}
onMounted(() => {
  setOrgMembers()
})
interface Config {
  shiftsPerDay: string
  minPeople: string
  maxPeople: string
  weeks: string
  minShifts: string
  maxShifts: string
  locations: string
  minFreeShifts: string
  maxFreeShifts: string
  startWeek: string
  endWeek: string
  exclude_name: string[]
}

const config = ref<Config>({
  shiftsPerDay: '4', // 每日班次数量
  minPeople: '1', // 每个班次人数范围
  maxPeople: '1', // 每个班次人数范围
  weeks: '1', // 排班周期(周)
  minShifts: '4', // 每人每个周期内班次范围
  maxShifts: '4', // 每人每个周期内班次范围
  locations: '2', // 值班地点数量
  minFreeShifts: '4', // 一周（5天）内空闲班次范围
  maxFreeShifts: '4', // 一周（5天）内空闲班次范围
  startWeek: '1', // 值班时间起始周
  endWeek: '18', // 值班时间结束周
  exclude_name: [], // 排除m
})
const configTypes = ref(['勤工俭学办公室助理', '敬请期待...'])
const currentConfigType = ref(0) // 初始值为 0，确保它在数组范围内

const showConfigDropdown = ref(false) // 显示配置下拉菜单

const toggleConfigType = (): void => {
  // 切换配置类型
  showConfigDropdown.value = !showConfigDropdown.value
}

const selectConfigType = (index: number): void => {
  // 选择配置类型
  currentConfigType.value = index
  showConfigDropdown.value = false
  console.log(currentConfigType.value)
}

// 原始数据
const rawData = ref<any[]>([])
const startScheduling = async (): Promise<void> => {
  if (currentConfigType.value === 1) {
    ElMessage.error('敬请期待...')
    return
  }

  const week_map = {
    周一: 1,
    周二: 2,
    周三: 3,
    周四: 4,
    周五: 5,
  }
  const params = {
    days_per_week: parseInt(config.value.weeks),
    shift_per_day: parseInt(config.value.shiftsPerDay),
    max_shifts_per_employee: parseInt(config.value.maxShifts),
    min_shifts_per_employee: parseInt(config.value.minShifts),
    locations: parseInt(config.value.locations),
    max_free_shifts_per_location: parseInt(config.value.maxFreeShifts),
    min_free_shifts_per_location: parseInt(config.value.minFreeShifts),
    max_employees: parseInt(config.value.maxPeople),
    min_employees: parseInt(config.value.minPeople),
    mandatory_shifts: tags.value.reduce((acc: Record<string, string>, tag) => {
      const weekValue = week_map[tag.week as keyof typeof week_map]
      const numberValue = parseInt(tag.number)
      const key = `(${weekValue}, ${numberValue})`
      const value = tag.isNull.toString()
      acc[key] = value === 'false' ? 'must_not_have' : 'must_have'
      return acc
    }, {}),
  }
  const valid_times = timeSlots.value.map(slot => slot.time)

  console.log(config.value.startWeek)
  console.log(config.value.endWeek)
  console.log(valid_times)
  console.log(config.value.exclude_name)
  console.log(params)
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const res = await api.getOrgDutyTable(
      org_id.value,
      config.value.startWeek,
      config.value.endWeek,
      valid_times,
      config.value.exclude_name,
      params
    )
    console.log(res)
    rawData.value = res.data
    if (rawData.value.length === 0) {
      ElMessage.error('无可行解')
    }
  } catch (error) {
    console.error('获取组织排班表异常', error)
    throw error
  } finally {
    loading.close()
  }
}

interface Tag {
  // 标签
  week: string
  number: string
  isNull: boolean
}
interface TimeSlot {
  // 班次时间段
  time: string
}

// 选项配置
const weekOptions = ['周一', '周二', '周三', '周四', '周五'] // 星期
const nullOptions = [
  // 是否为空
  { label: '必须有人', value: true }, // 必须有人
  { label: '必须无人', value: false }, // 必须无人
]

// 响应式数据
const selected = reactive({
  // 选择
  week: '',
  number: '',
  isNull: false,
})

const tags = ref<Tag[]>([]) // 标签
const timeSlots = ref<TimeSlot[]>([
  { time: '1-2节\n09:00-10:20' },
  { time: '3-4节\n10:40-12:00' },
  { time: '7-8节\n14:00-15:20' },
  { time: '9-10节\n15:30-16:50' },
]) // 班次时间段
// 计算属性
const isSelectionComplete = computed(() => {
  // 选择是否完成
  return selected.week && selected.number && selected.isNull !== null
})

// 方法
const addTag = () => {
  console.log(tags.value)
  // 判断是否已存在
  if (tags.value.some(tag => tag.week === selected.week && tag.number === selected.number)) {
    ElMessage.error('标签已存在')
    return
  }
  // 添加标签
  if (!isSelectionComplete.value) return

  tags.value.push({ ...selected })
  resetSelections()
  console.log(tags.value)
}

const removeTag = (index: number) => {
  // 删除标签
  tags.value.splice(index, 1)
}

const updateTimeSlots = () => {
  // 更新班次时间段
  timeSlots.value = []
  // 初始化 time_slots
  time_slots.value = [
    '1-2节\n09:00-10:20',
    '3-4节\n10:40-12:00',
    '5-6节\n12:30-13:50',
    '7-8节\n14:00-15:20',
    '9-10节\n15:30-16:50',
    '11-12节\n17:00-18:20',
    '13-14节\n19:00-20:20',
    '15-16节\n20:30-21:50',
  ]
}

const removeTimeSlot = (index: number, time: string) => {
  // 删除班次时间段
  timeSlots.value.splice(index, 1)
  // time_slots 中添加已删除的时间段
  time_slots.value.push(time)
  // 排序
  time_slots.value.sort((a, b) => {
    const timeA = a.split('-')[0]
    const timeB = b.split('-')[0]
    return parseInt(timeA) - parseInt(timeB)
  })
  // 排序 timeSlots
  timeSlots.value.sort((a, b) => {
    const timeA = a.time.split('-')[0]
    const timeB = b.time.split('-')[0]
    return parseInt(timeA) - parseInt(timeB)
  })
}

const formatTag = (tag: Tag) => {
  // 格式化标签
  return `${tag.week}的第${tag.number}班次${tag.isNull ? '必须有人' : '必须无人'}`
}

const resetSelections = () => {
  // 重置选择
  selected.week = ''
  selected.number = ''
  selected.isNull = false
}

// 新增的标签输入框相关逻辑
const time_slots = ref<string[]>([
  // 班次时间段
  '1-2节\n09:00-10:20',
  '3-4节\n10:40-12:00',
  '5-6节\n12:30-13:50',
  '7-8节\n14:00-15:20',
  '9-10节\n15:30-16:50',
  '11-12节\n17:00-18:20',
  '13-14节\n19:00-20:20',
  '15-16节\n20:30-21:50',
])

const selectedTimeSlot = ref('') // 选择班次时间段

const addTimeSlotTag = () => {
  // 添加班次时间段
  if (selectedTimeSlot.value && timeSlots.value.length < parseInt(config.value.shiftsPerDay)) {
    timeSlots.value.push({ time: selectedTimeSlot.value })
    // time_slots 中删除已添加的时间段
    time_slots.value = time_slots.value.filter((slot: string) => slot !== selectedTimeSlot.value)

    // 排序
    time_slots.value.sort((a, b) => {
      const timeA = a.split('-')[0]
      const timeB = b.split('-')[0]
      return parseInt(timeA) - parseInt(timeB)
    })
    // 排序 timeSlots
    timeSlots.value.sort((a, b) => {
      const timeA = a.time.split('-')[0]
      const timeB = b.time.split('-')[0]
      return parseInt(timeA) - parseInt(timeB)
    })
    console.log(time_slots.value)
    selectedTimeSlot.value = ''
  }
}

// 响应式数据
const currentSchedule = ref(0) // 当前选中的排班表索引
const totalDays = 5 // 总天数
const totalShifts = 4 // 总班次数

// 计算属性
const schedules = computed(() => {
  return rawData.value.map((schedule: any) => {
    const organized: Record<string, string[]> = {}
    schedule.forEach(([name, loc, day, shift]: [string, string, number, number]) => {
      const key = `${loc}-${day}-${shift}`
      if (!organized[key]) organized[key] = []
      organized[key].push(name)
    })
    return organized
  })
})

const locations = computed(() => {
  const locs = new Set()
  rawData.value[currentSchedule.value].forEach((item: any) => locs.add(item[1]))
  return Array.from(locs).sort()
})

// 方法
const getStaff = (location: string, day: number, shift: number) => {
  const key = `${location}-${day}-${shift}`
  return schedules.value[currentSchedule.value][key] || []
}

// 添加计算属性以确定按钮是否应被禁用
const isFirstSchedule = computed(() => currentSchedule.value === 0)
const isLastSchedule = computed(() => currentSchedule.value === schedules.value.length - 1)

// 添加方法以切换排班表
const prevSchedule = () => {
  if (currentSchedule.value > 0) {
    currentSchedule.value -= 1
  }
}

const nextSchedule = () => {
  if (currentSchedule.value < schedules.value.length - 1) {
    currentSchedule.value += 1
  }
}

const getColorForStudent = (name: string) => {
  // 简单的哈希函数
  const hash = name.split('').reduce((acc, char) => {
    return acc + char.charCodeAt(0)
  }, 0)

  // 使用哈希值生成颜色
  let color = `#${((hash * 1234567) % 0xffffff).toString(16).padStart(6, '0')}`

  // 将 HEX 转换为 HSL
  const hexToHsl = (hex: string) => {
    hex = hex.replace('#', '')
    const r = parseInt(hex.substring(0, 2), 16) / 255
    const g = parseInt(hex.substring(2, 4), 16) / 255
    const b = parseInt(hex.substring(4, 6), 16) / 255

    const max = Math.max(r, g, b)
    const min = Math.min(r, g, b)
    let h = 0,
      s = 0,
      l = (max + min) / 2

    if (max !== min) {
      const d = max - min
      s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
      switch (max) {
        case r:
          h = (g - b) / d + (g < b ? 6 : 0)
          break
        case g:
          h = (b - r) / d + 2
          break
        case b:
          h = (r - g) / d + 4
          break
      }
      h /= 6
    }

    return [h * 360, s * 100, l * 100]
  }

  // 将 HSL 转换为 HEX
  const hslToHex = (h: number, s: number, l: number) => {
    l /= 100
    const a = (s * Math.min(l, 1 - l)) / 100
    const f = (n: number) => {
      const k = (n + h / 30) % 12
      const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1)
      return Math.round(255 * color)
        .toString(16)
        .padStart(2, '0')
    }
    return `#${f(0)}${f(8)}${f(4)}`
  }

  // 调整亮度
  const [h, s, l] = hexToHsl(color)
  const newL = Math.min(80, l + 20) // 增加亮度，但不超过 80%

  // 返回新的颜色
  return hslToHex(h, s, newL)
}
// 计算亮度
const getLuminance = (hexColor: string): number => {
  const hex = hexColor.replace('#', '')
  const r = parseInt(hex.substring(0, 2), 16) / 255
  const g = parseInt(hex.substring(2, 4), 16) / 255
  const b = parseInt(hex.substring(4, 6), 16) / 255
  return 0.2126 * r + 0.7152 * g + 0.0722 * b
}
const getTextColor = (backgroundColor: string): string => {
  const luminance = getLuminance(backgroundColor)
  return luminance > 0.5 ? '#000000' : '#ffffff'
}
</script>
